package com.uml.umlwork.config.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.uml.umlwork.config.annotation.AdminToken;
import com.uml.umlwork.config.annotation.PassToken;
import com.uml.umlwork.config.annotation.TeacherToken;
import com.uml.umlwork.config.annotation.UserLoginToken;
import com.uml.umlwork.entity.User;
import com.uml.umlwork.entity.enumeration.RoleEnum;
import com.uml.umlwork.mapper.TeacherMapper;
import com.uml.umlwork.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Optional;

/**
 * 通过反射实现登录检验
 *
 * @author Siki
 * @date 2020/12/21
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    UserMapper userMapper;
    @Autowired
    TeacherMapper teacherMapper;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        // 备注：方法上没有PassToken注解也不用验证
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        Class<?> methodClass = method.getDeclaringClass();

        // 检查类是否有pass注释，有则跳过认证
        if (methodClass.isAnnotationPresent(PassToken.class)) {
            return true;
        }
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        // 检查类有没有需要用户权限的注解
        if (methodClass.isAnnotationPresent(UserLoginToken.class) || method.isAnnotationPresent(UserLoginToken.class)) {
            // 认证
            Assert.notNull(token, "无token,请登陆");
            // 获取 token 中的 user id
            String userId;
            try {
                userId = JWT.decode(token).getAudience().get(0);
            } catch (JWTDecodeException j) {
                // 内部异常
                throw new RuntimeException("jwt异常");
            }
            User user = Optional.ofNullable(userMapper.selectById(userId))
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            if (method.isAnnotationPresent(AdminToken.class) || methodClass.isAnnotationPresent(AdminToken.class)) {
                Assert.isTrue(user.getRole().equals(RoleEnum.ADMIN),
                        "该接口只有管理员能访问");
            } else if (method.isAnnotationPresent(TeacherToken.class) || methodClass.isAnnotationPresent(TeacherToken.class)) {
                Assert.isTrue(user.getRole().equals(RoleEnum.TEACHER) || user.getRole().equals(RoleEnum.ADMIN),
                        "该接口只有教师才能访问");
            }
            // 验证 token
            JWTVerifier jwtVerifier = JWT.require(Algorithm
                    .HMAC256(user.getPassword())).build();
            try {
                jwtVerifier.verify(token);
            } catch (JWTVerificationException e) {
                throw new RuntimeException("jwt验证错误");
            }
            httpServletRequest.setAttribute("userId", userId);
            return true;

        }

        return true;
    }

    /**
     * 一切从简
     *
     * @author: siki
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}